#!/usr/bin/python
# -*- coding: UTF-8 -*-

# GB28181协议相关

import hashlib
import requests
from typing import Any, Dict


class ObjectDict(Dict[str, Any]):

    def __getattr__(self, name: str) -> Any:
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name: str, value: Any) -> None:
        self[name] = value


class ApiHelper_LiveNVR(object):

    def __init__(self, host, username, password):
        self.host = host
        self.username = username
        self.password = password

    def check_result(self, response):
        if response.status_code == 200:
            params = ObjectDict(**(response.json()))
            return params
        raise ValueError("接口请求失败")

    @property
    def login_token(self):
        hl = hashlib.md5()
        # Tips
        # 此处必须声明encode
        # 若写法为hl.update(str) 报错为： Unicode-objects must be encoded before hashing
        hl.update(self.password.encode(encoding='utf-8'))
        url = f'{self.host}/api/v1/login?username={self.username}&password={hl.hexdigest()}'
        result = requests.get(url)
        return self.check_result(result)['LiveQing']['Body']['Token']

    def get_user_ID_list(self):
        """
        用户列表
        """

        url = f'{self.host}/api/v1/user/list'
        headers = {
            'Cookie': "token={}".format(self.login_token)
        }
        result = requests.get(url, headers=headers)

        return [i['ID'] for i in self.check_result(result)['UserList']]

    def get_user_channellist(self):
        """
        获取所有用户通道列表/api/v1/user/channellist
        """
        ID_list = self.get_user_ID_list()
        ChannelList = []
        for ID in ID_list:
            url = f'{self.host}/api/v1/user/channellist?id={ID}'
            headers = {
                'Cookie': "token={}".format(self.login_token)
            }
            result = requests.get(url, headers=headers)
            ChannelList.extend(self.check_result(result)['ChannelList'])
            return ChannelList

    def get_channel_list_by_live_gbs(self):
        """
        通过liveNVR通道列表
        """
        url = f'{self.host}/api/v1/getchannels'
        headers = {
            'Cookie': "token={}".format(self.login_token)
        }
        result = requests.get(url, headers=headers)
        return self.check_result(result)['LiveQing']['Body']

    def live_broadcast(self):
        """
        播放单个通道直播
        """
        live_broadcast_list = []
        channel_list = self.get_user_channellist()
        for channel in channel_list:
            Channel = channel['Channel']
            IP = channel['IP']
            url = f'{self.host}/api/v1/getchannelstream?Channel={Channel}'
            headers = {
                'Cookie': f"token={self.login_token}"
            }
            result = requests.get(url, headers=headers)
            ChannelName = self.check_result(result)['LiveQing']['Body']['ChannelName']
            URL = self.check_result(result)['LiveQing']['Body']['URL']
            live_broadcast_list.append({"Channel": Channel, "ChannelName": ChannelName, "URL": URL, "IP": IP})
        return live_broadcast_list


if __name__ == '__main__':
    config = {
        "host": "http://172.16.111.103:10800",
        "username": "admin",
        "password": "admin"
    }
    a = ApiHelper_LiveNVR(**config)
    # print(a.login_token)

    # print(a.live_broadcast())

    # print(a.get_device_list_by_live_gbs())
    # print(a.get_channel_list_by_live_gbs())
    # print(a.get_user_channellist())
    print(a.live_broadcast())
    # print(a.live_broadcast())
